import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;
import { PalBattleHeroSaveData } from "./PalBattleSystem";
import { DataManager } from './DataManager';

export interface PlayerData {
    UUID: string;
    heros: PalBattleHeroSaveData[];
}

@ccclass('PlayerManager')
export class PlayerManager extends Component {
    public static instance = null;
    public static getInstance<PlayerManager>(): PlayerManager {
        if (!this.instance) this.instance = new this() as PlayerManager;
        return this.instance;
    }
    installSingletion() {
        if (!PlayerManager.instance) {
            PlayerManager.instance = this;
        }
    }
    protected onLoad(): void {
        this.installSingletion();
    }

    player: PlayerData[] = [];

    setHero(UUID: string, hero: PalBattleHeroSaveData) {
        const player = this.player.find((item) => item.UUID === UUID);
        if (!player) {
            this.player.push({
                UUID: UUID,
                heros: [hero]
            });
        } else {
            this.player.find((item) => item.UUID === UUID).heros.push(hero);
        }
        this.saveLocalStorage();
    }

    getHeros(UUID: string): PalBattleHeroSaveData[] {
        return this.player.find((item) => item.UUID === UUID).heros;
    }

    getExp(level: number) {
        return level * 100;
    }

    heroLevelUp(uuid: string) {
        const hero = this.getHeros(uuid).find((item) => item.UUID === uuid);
        const heroOriginData = (DataManager.instance as DataManager).getHeroOriginData(hero.heroID);
        if (!hero) {
            return;
        }
        hero.level++;
        hero.exp = 0;
        hero.maxExp = this.getExp(hero.level);
        hero.hp = hero.hp + (heroOriginData.levelUp['hp'] || 0);
        hero.mp = hero.mp + (heroOriginData.levelUp['mp'] || 0);
        hero.武术 = hero.武术 + (heroOriginData.levelUp['武术'] || 0);
        hero.灵力 = hero.灵力 + (heroOriginData.levelUp['灵力'] || 0);
        hero.防御 = hero.防御 + (heroOriginData.levelUp['防御'] || 0);
        hero.身法 = hero.身法 + (heroOriginData.levelUp['身法'] || 0);
        hero.吉运 = hero.吉运 + (heroOriginData.levelUp['吉运'] || 0);
        this.saveLocalStorage();
    }

    saveLocalStorage() {
        localStorage.setItem('player', JSON.stringify(this.player));
    }
    getLocalStorage() {
        return JSON.parse(localStorage.getItem('player'));
    }
    saveToFile() {

    }

    private generatorUUID(): string {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
}


